package com.example.demo.config;

import com.example.demo.bean.User;
import com.example.demo.exception.CodeMsg;
import com.example.demo.exception.GlobalException;
import com.example.demo.redis.RedisServer;
import com.example.demo.redisPrefix.UserPrefixAndExpireSecond;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.groups.ConvertGroup;

//自定义参数拦截的类
@Configuration
public class UserArgumentResolver implements HandlerMethodArgumentResolver {
    
    @Autowired
    RedisServer redisServer;

    //要拦截的参数类型
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        Class<?> parameterType = methodParameter.getParameterType();
        //如果参数是User就拦截下来交给resolveArgument函数处理
        return parameterType==User.class;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest nativeRequest =(HttpServletRequest) nativeWebRequest.getNativeRequest();
        HttpServletResponse nativeResponse = (HttpServletResponse)nativeWebRequest.getNativeResponse();
        //获得浏览器中存储的cookie
        Cookie[] cookies = nativeRequest.getCookies();
        String tokenValue = getCookieTokenValue(cookies,"token");
        if (tokenValue==null){
            throw  new GlobalException(CodeMsg.SERVER_ERROR);
        }
        //获的token从redis中取出对应的user
        User user = redisServer.get(UserPrefixAndExpireSecond.re_token, tokenValue, User.class);
        System.out.println(user);
        return user;
    }

    //从cookie里面获取对呀的token
   public String getCookieTokenValue(Cookie[] cookies,String cookieNameToken){
        if (cookies==null||cookies.length==0){
            return null;
        }else {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(cookieNameToken)){
                    return cookie.getValue();
                }
            }
        }
        return null;
   }
}
